package com.tb.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.client.android.Utils.ZXingUtils;

public class MainActivity extends AppCompatActivity {

    private Button scanButton;
    private EditText etCreate;
    private ImageView qrCode;

    //解码调用
    private final View.OnClickListener buttonListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ZXingUtils.startCaptureForResult((Activity) getContext(), 0);
        }
    };
    //制码调用
    private final View.OnKeyListener textListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                String text = ((TextView) view).getText().toString();
                if (!text.isEmpty()) {
                    qrCode.setImageBitmap(ZXingUtils.getBitmapByString(text));
                }
                return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scanButton = (Button) findViewById(R.id.button_scan);
        etCreate = (EditText) findViewById(R.id.et_create);
        qrCode = (ImageView) findViewById(R.id.imageView);
        scanButton.setOnClickListener(buttonListener);
        etCreate.setOnKeyListener(textListener);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String scanResult = data.getStringExtra("result_string");
            Log.d("scanResult:", scanResult);
            etCreate.setText(scanResult);
        }
    }

    private Context getContext() {
        return this;
    }

}
